<template>
	<view class="wrapper" v-if="blog">
		<!-- #ifndef MP-WEIXIN -->
		<navBar :title="blog.title"></navBar>
		<!-- #endif -->
		<!-- 封面 -->
		<view class="cover">
			<image :src="blog.cover" mode="widthFix"></image>
			<view class="mask">
				<view class="title">{{ blog.title }}</view>
				<view class="publisher">
					<view class="publish_l">
						<view class="avtar"><image :src="blog.userAvatar || '../../static/logo.png'"></image></view>
						<text class="username">{{ blog.userName }}</text>
					</view>
					<view class="publish_r">
						<view class="zan">
							<u-icon name="thumb-up" color="#fff" size="18px"></u-icon>
							{{ blog.like_count }}
						</view>
						丨
						<view class="createTime">
							{{ $u.timeFormat(new Date(blog.createdAt), 'yyyy年mm月dd日 hh:MM:ss') }}发布
						</view>
					</view>
				</view>
			</view>
		</view>
		<!-- 内容 -->
		<view class="content"><view v-html="blog.content"></view></view>

		<!-- 评论 -->
		<view class="list">
			<view class="blog_com">最新评论({{ blog.comment_count - 1 < 0 ? 0 : blog.comment_count - 1 }})</view>
			<view class="list_item" v-for="item in commentList" :key="item.id">
				<!-- 父评论 -->
				<view class="list_con">
					<view class="list_item_l" @click="reply(item.id, item.userName)">
						<view class="commentor">
							<view class="avatar"><image :src="item.userAvatar"></image></view>
							<view class="comment_info">
								<view class="commentor_name">{{ item.userName }}</view>
								<view class="comment_time">
									{{ $u.timeFormat(new Date(item.createdAt), 'yyyy年mm月dd日 hh:MM:ss') }}
									<text
										class="del"
										@click.stop="del(item.id)"
										v-if="userInfo && (userInfo.id == item.userId || userInfo.id == item.authorId)"
									>
										删除
									</text>
								</view>
							</view>
						</view>
						<view class="comment_text">{{ item.content }}</view>
					</view>
					<view class="list_item_r">
						<u-icon
							:name="isLike.includes(item.id) ? `thumb-up-fill` : `thumb-up`"
							color="#9ca8b8"
							size="7vw"
							@click="comment_zan(item.id)"
						></u-icon>
						<view class="like_coount">
							<u-badge
								numberType="overflow"
								max="99"
								:value="item.likeCount"
								:showZero="true"
								:inverted="true"
								color="#9ca8b8"
							></u-badge>
						</view>
					</view>
				</view>
				<!-- 回复评论模块 -->
				<view class="reply_box" v-if="item.sons.length" v-for="son in item.sons" :key="son.id">
					<view class="reply_l" @click="reply(son.id, son.userName)">
						<!-- 回复评论的用户 -->
						<view class="reply">
							<view class="reply_info">
								<!-- 回复的用户 -->
								<view class="reply_user">
									<view class="reply_user_img"><image :src="son.userAvatar"></image></view>
									<text>{{ son.userName }}</text>
								</view>
								<u-icon class="icon" name="rewind-right" size="5vw"></u-icon>
								<!-- 被回复的用户 -->
								<text>{{ son.beRepliedUserName }}</text>
							</view>
							<view class="reply_time">
								{{ $u.timeFormat(new Date(son.createdAt), 'yyyy年mm月dd日 hh:MM:ss') }}
								<text
									class="del"
									@click.stop="del(son.id, son.beRepliedUserId)"
									v-if="userInfo && (userInfo.id == son.userId || userInfo.id == son.authorId)"
								>
									删除
								</text>
							</view>
						</view>
						<!-- 回复评论内容 -->
						<view class="reply_con">{{ son.content }}</view>
					</view>
					<view class="reply_r">
						<u-icon
							:name="isLike.includes(son.id) ? `thumb-up-fill` : `thumb-up`"
							color="#9ca8b8"
							size="7vw"
							@click="comment_zan(son.id)"
						></u-icon>
						<view class="like_coount">
							<u-badge
								numberType="overflow"
								max="99"
								:value="son.likeCount < 0 ? 0 : son.likeCount"
								:showZero="true"
								:inverted="true"
								color="#9ca8b8"
							></u-badge>
						</view>
					</view>
				</view>
			</view>
			<u-loadmore v-if="commentList.length" height="40px" marginTop="0" marginBottom="0" :status="status" />
			<u-empty v-else mode="list" text="暂无评论"></u-empty>
		</view>

		<!-- 底部关注点赞模块 -->
		<view class="footer">
			<view class="inp">
				<u--input
					@change="getContent"
					@blur="blur"
					:value="content"
					shape="circle"
					border="none"
					:placeholder="placeholder"
					:focus="isFocus"
				></u--input>
				<u-icon @click="clear" name="close" color="#9ca8b8" size="16"></u-icon>
			</view>
			<view class="hudong">
				<view class="zan" @click="zan">
					<u-icon :name="isZan ? 'thumb-up-fill' : 'thumb-up'" size="6vw" color="#9ca8b8"></u-icon>
					赞
				</view>
				<view class="care" @click="care">
					<u-icon :name="isCare ? 'heart-fill' : 'heart'" size="6vw" color="#9ca8b8"></u-icon>
					关注
				</view>
				<view class="comment" @click="comment">
					<u-icon name="chat" size="6vw" color="#9ca8b8"></u-icon>
					评论
				</view>
			</view>
		</view>

		<!-- 弹出层 -->
		<u-popup :show="show" @close="close" mode="center" round="5vw">
			<view class="login_wrapper"><login @closeLogin="show = false" :blogid="blog.id"></login></view>
		</u-popup>
	</view>
</template>

<script>
import {
	getBlogById,
	getLikeBlogs,
	likeBlog,
	getLikeUser,
	likeUser,
	getCurrentBlogComments,
	createComment,
	likeComment,
	deleteComment
} from '@/config/api.js';
import { mapState } from 'vuex';
export default {
	data() {
		return {
			// 博客信息
			blog: null,
			isZan: false,
			isCare: false,
			// 评论内容
			content: '',
			// 当前博客的评论列表
			commentList: [],
			// 评论默认显示多少条
			limit: 10,
			// 展示弹出层
			show: false,
			// 回复的父评论id
			parentCommentId: '',
			// 输入框自动获取焦点
			isFocus: false,
			placeholder: '说点啥呗',
			// 是否给评论点过赞
			isLike: [],
			// 是否加载下一页
			isNext: false,
			// 底部上拉加载的状态值
			status: 'loadmore',
			// 数据总数
			count: ''
		};
	},
	async onLoad(e) {
		await this.getBlog(e.blogid);
		this.getLikeBlogs();
		this.getLikeUser();
		// #ifndef MP-WEIXIN
		this.getCurrentBlogComment();
		// #endif
	},
	// 滚动到底部的生命周期
	onReachBottom() {
		// 正在加载，返回
		if (this.isNext) return;
		// 若没有数据，不执行loading，直接return
		if (this.limit >= this.count) {
			this.status = 'nomore';
			return;
		}
		this.isNext = true;
		// 若还有数据
		this.status = 'loading';
		setTimeout(async () => {
			this.limit += 10;
			await this.getCurrentBlogComment(this.limit);
			this.isNext = false;
			if (this.limit >= this.count) {
				this.status = 'nomore';
			} else {
				this.status = 'loadmore';
			}
		}, 300);
	},
	methods: {
		// 根据ID查找博客
		async getBlog(id) {
			// #ifndef MP-WEIXIN
			const res = await getBlogById(id);
			console.log('当前博客', res);
			this.blog = res;
			// #endif
			// #ifdef MP-WEIXIN
			uni.request({
				url: 'https://eggblog.bluej.cn/api/blog/search',
				method: 'GET',
				data: {
					id,
					projectId: 155
				},
				success: res => {
					console.log('当前博客', res);
					this.blog = res.data.data;
					// 利用正则，给小程序的富文本标签中图片添加样式
					this.blog.content = this.blog.content.replace(/\<img/gi, `<img style="width: 100%"`);
					uni.setNavigationBarTitle({
						title: this.blog.title
					});
					this.getCurrentBlogComment();
				}
			});
			// #endif
		},
		// 获取点赞过的博客
		async getLikeBlogs() {
			// 未登录
			if (!this.userInfo) return;

			// #ifndef MP-WEIXIN
			const res = await getLikeBlogs(this.userInfo.token);
			// 动态绑定是否已点赞
			this.isZan = res.rows.some(ele => ele.blogId == this.blog.id);
			// #endif

			// #ifdef MP-WEIXIN
			uni.request({
				url: 'https://eggblog.bluej.cn/api/user/getLikeBlog',
				method: 'GET',
				data: {},
				header: {
					'x-token': this.userInfo.token
				},
				success: res => {
					console.log(res);
					// 动态绑定是否已点赞
					this.isZan = res.data.data.rows.some(ele => ele.blogId == this.blog.id);
				}
			});
			// #endif
		},
		// 获取关注的用户
		async getLikeUser() {
			// 未登录
			if (!this.userInfo) return;

			// #ifndef MP-WEIXIN
			const res = await getLikeUser(this.userInfo.token);
			// 动态绑定是否已关注
			this.isCare = res.rows.some(ele => ele.followUserId == this.blog.userId);
			// #endif

			// #ifdef MP-WEIXIN
			uni.request({
				url: 'https://eggblog.bluej.cn/api/user/getLikeUser',
				method: 'GET',
				data: {},
				header: {
					'x-token': this.userInfo.token
				},
				success: res => {
					console.log(res);
					// 动态绑定是否已关注
					this.isCare = res.data.data.rows.some(ele => ele.followUserId == this.blog.userId);
				}
			});
			// #endif
		},
		// 点赞
		async zan() {
			// 未登录
			if (!this.userInfo) {
				this.show = true;
				return;
			}
			uni.showLoading();
			try {
				// #ifndef MP-WEIXIN
				const res = await likeBlog(this.blog.id, this.userInfo.token);
				this.isZan = !this.isZan;
				uni.hideLoading();
				if (this.isZan) {
					uni.showToast({
						title: '点赞成功'
					});
				} else {
					uni.showToast({
						title: '取消点赞成功'
					});
				}
				// #endif
				// #ifdef MP-WEIXIN
				uni.request({
					url: 'https://eggblog.bluej.cn/api/blog/likeBlog',
					method: 'POST',
					data: {
						projectId: 155,
						id: this.blog.id
					},
					header: {
						'x-token': this.userInfo.token
					},
					success: res => {
						console.log(res);
						this.isZan = !this.isZan;
						uni.hideLoading();
						if (this.isZan) {
							uni.showToast({
								title: '点赞成功'
							});
						} else {
							uni.showToast({
								title: '取消点赞成功'
							});
						}
					}
				});
				// #endif
			} catch (err) {
				console.log(err);
			}
		},
		// 关注
		async care() {
			// 未登录
			if (!this.userInfo) {
				this.show = true;
				return;
			}
			uni.showLoading();
			try {
				// #ifndef MP-WEIXIN
				const res = await likeUser(this.blog.userId, this.userInfo.token);
				this.isCare = !this.isCare;
				uni.hideLoading();
				if (this.isCare) {
					uni.showToast({
						title: '关注成功'
					});
				} else {
					uni.showToast({
						title: '取消关注成功'
					});
				}
				// #endif
				// #ifdef MP-WEIXIN
				uni.request({
					url: 'https://eggblog.bluej.cn/api/user/follow',
					method: 'POST',
					data: {
						projectId: 155,
						id: this.blog.userId
					},
					header: {
						'x-token': this.userInfo.token
					},
					success: res => {
						console.log(res);
						this.isCare = !this.isCare;
						uni.hideLoading();
						if (this.isCare) {
							uni.showToast({
								title: '关注成功'
							});
						} else {
							uni.showToast({
								title: '取消关注成功'
							});
						}
					}
				});
				// #endif
			} catch (err) {
				console.log(err);
			}
		},
		// 获取当前博客评论
		async getCurrentBlogComment(limit) {
			// #ifndef MP-WEIXIN
			const res = await getCurrentBlogComments(this.blog.id, limit);
			console.log('获取当前博客评论', res);
			this.count = res.count;
			let arr = [];
			// 取出一级评论
			res.rows.forEach(ele => {
				if (ele.parentCommentId == 0) {
					ele.sons = [];
					arr.push(ele);
				}
			});
			// 取出次级评论，添加到一级评论的sons数组中
			res.rows.forEach(ele => {
				if (ele.parentCommentId == 0) return;
				arr.forEach(parent => {
					if (parent.id == ele.parentCommentId) {
						parent.sons.push(ele);
						hander(parent);
					}
				});
			});
			// 递归查找 子评论回复子评论
			function hander(arr_parent) {
				res.rows.forEach((ele, index) => {
					if (ele.parentCommentId == 0) return;
					arr_parent.sons.forEach(parent => {
						if (parent.id == ele.parentCommentId) {
							if (arr_parent.sons.includes(ele)) {
								return;
							} else {
								arr_parent.sons.push(ele);
								hander(arr_parent);
							}
						}
					});
				});
			}
			this.commentList = arr;
			// #endif

			// #ifdef MP-WEIXIN
			uni.request({
				url: 'https://eggblog.bluej.cn/api/comment/get',
				method: 'GET',
				data: {
					id: this.blog.id,
					projectId: 155,
					offset: 1,
					limit: limit || 10
				},
				success: res => {
					console.log('获取当前博客评论', res.data.data);
					this.count = res.data.data.count;
					let arr = [];
					// 取出一级评论
					res.data.data.rows.forEach(ele => {
						if (ele.parentCommentId == 0) {
							ele.sons = [];
							arr.push(ele);
						}
					});
					// 取出次级评论，添加到一级评论的sons数组中
					res.data.data.rows.forEach(ele => {
						if (ele.parentCommentId == 0) return;
						arr.forEach(parent => {
							if (parent.id == ele.parentCommentId) {
								parent.sons.push(ele);
								hander(parent);
							}
						});
					});
					// 递归查找 子评论回复子评论
					function hander(arr_parent) {
						res.data.data.rows.forEach((ele, index) => {
							if (ele.parentCommentId == 0) return;
							arr_parent.sons.forEach(parent => {
								if (parent.id == ele.parentCommentId) {
									if (arr_parent.sons.includes(ele)) {
										return;
									} else {
										arr_parent.sons.push(ele);
										hander(arr_parent);
									}
								}
							});
						});
					}
					this.commentList = arr;
				}
			});
			// #endif
			console.log(this.commentList);
		},
		// 获取输入框内容
		getContent(e) {
			this.content = e;
		},
		// 评论
		async comment() {
			// 未登录
			if (!this.userInfo) {
				this.show = true;
				return;
			}
			if (!this.content)
				return uni.showToast({
					icon: 'none',
					title: '评论不能为空'
				});
			uni.showLoading();
			try {
				// #ifndef MP-WEIXIN
				if (this.parentCommentId) {
					// 回复评论
					await createComment(this.blog.id, this.content, this.userInfo.token, this.parentCommentId);
				} else {
					// 直接评论
					await createComment(this.blog.id, this.content, this.userInfo.token);
				}
				uni.hideLoading();
				uni.showToast({
					title: '评论成功'
				});
				this.content = '';
				// 重新获取评论
				this.getCurrentBlogComment(this.limit);
				this.getBlog(this.blog.id);
				// #endif

				// #ifdef MP-WEIXIN
				uni.request({
					url: 'https://eggblog.bluej.cn/api/comment/create',
					method: 'POST',
					data: {
						blogId: this.blog.id,
						projectId: 155,
						content: this.content,
						parentCommentId: this.parentCommentId ? this.parentCommentId : undefined
					},
					header: {
						'x-token': this.userInfo.token
					},
					success: res => {
						console.log(res);
						if (res.data.code == 409) {
							uni.hideLoading();
							uni.showToast({
								title: res.data.msg,
								icon: 'error'
							});
							return;
						}
						uni.hideLoading();
						uni.showToast({
							title: '评论成功'
						});
						this.content = '';
						// 重新获取评论
						this.getCurrentBlogComment(this.limit);
						this.getBlog(this.blog.id);
					}
				});
				// #endif
			} catch (err) {
				console.log(err);
				if (!err.data) return;
				uni.hideLoading();
				uni.showToast({
					title: err.data.msg,
					icon: 'error'
				});
			}
		},
		// 获取回复评论的id
		reply(commentId, uname) {
			console.log('回复评论', commentId, uname);
			// 获取焦点
			this.content = '';
			this.isFocus = true;
			this.placeholder = `回复 ${uname}`;
			this.parentCommentId = commentId;
		},
		blur() {
			this.isFocus = false;
		},
		// 点击右侧叉号触发
		clear() {
			if (this.content) {
				this.content = '';
				this.isFocus = true;
				return;
			}
			this.placeholder = `说点啥呗`;
			this.parentCommentId = '';
		},
		// 点赞、取消点赞评论
		async likeComments(commentId) {
			// #ifndef MP-WEIXIN
			await likeComment(this.blog.id, commentId, this.userInfo.token);
			// 点赞后，重新获取评论更新视图
			this.getCurrentBlogComment(this.limit);
			// #endif
			// #ifdef MP-WEIXIN
			uni.request({
				url: 'https://eggblog.bluej.cn/api/comment/like',
				method: 'POST',
				data: {
					blogId: this.blog.id,
					projectId: 155,
					commentId: commentId
				},
				header: {
					'x-token': this.userInfo.token
				},
				success: res => {
					this.getCurrentBlogComment(this.limit);
				}
			});
			// #endif
		},
		// 点赞评论（接口数据没有该评论下是否点过赞的数据，故刷新页面会有点赞未激活的bug）
		comment_zan(commentId) {
			// 未登录
			if (!this.userInfo) {
				this.show = true;
				return;
			}
			try {
				if (this.isLike.includes(commentId)) {
					const index = this.isLike.findIndex(ele => ele == commentId);
					this.isLike.splice(index, 1);
					this.likeComments(commentId);
				} else {
					this.isLike.push(commentId);
					this.likeComments(commentId);
				}
			} catch (err) {
				console.log(err);
				uni.showToast({
					icon: 'error',
					title: '点赞失败'
				});
			}
		},
		// 弹出层
		close() {
			this.show = false;
		},
		// 删除评论
		del(commentId, beRepliedUserId) {
			uni.showModal({
				title: '提示',
				content: '确定删除该评论？',
				success: async res => {
					if (res.confirm) {
						// #ifndef MP-WEIXIN
						uni.showLoading();
						if (beRepliedUserId) {
							await deleteComment(commentId, this.userInfo.token, beRepliedUserId);
						} else {
							await deleteComment(commentId, this.userInfo.token);
						}
						uni.hideLoading();
						uni.showToast({
							title: '删除成功'
						});
						// 删除后，重新获取评论更新视图
						this.getCurrentBlogComment(this.limit);
						this.getBlog(this.blog.id);
						// #endif
						// #ifdef MP-WEIXIN
						uni.showLoading();
						uni.request({
							url: 'https://eggblog.bluej.cn/api/comment/delete',
							method: 'DELETE',
							data: {
								id: commentId,
								beRepliedUserId: beRepliedUserId,
								projectId: 155
							},
							header: {
								'x-token': this.userInfo.token
							},
							success: res => {
								uni.hideLoading();
								uni.showToast({
									title: '删除成功'
								});
								// 删除后，重新获取评论更新视图
								this.getCurrentBlogComment(this.limit);
								this.getBlog(this.blog.id);
							}
						});
						// #endif
					}
				}
			});
		}
	},
	computed: {
		...mapState(['userInfo'])
	}
};
</script>

<style lang="scss" scoped>
.wrapper {
	padding: 1vh 2vw 0;
	.cover {
		overflow: hidden;
		border-radius: 3vw;
		position: relative;
		width: 100%;
		image {
			display: block;
			width: 100%;
		}
		.mask {
			display: flex;
			flex-direction: column;
			justify-content: center;
			position: absolute;
			bottom: 0;
			width: 100%;
			height: 10vh;
			background-color: rgba(0, 0, 0, 0.35);
			color: #fff;
			.title {
				overflow: hidden;
				height: 5vh;
				line-height: 5vh;
				padding: 0 3vw;
				font-weight: 700;
				font-size: 20px;
			}
			.publisher {
				display: flex;
				justify-content: space-between;
				padding: 0 3vw;
				.publish_l,
				.publish_r {
					display: flex;
					align-items: center;
				}
				.avtar {
					width: 7vw;
					height: 7vw;
					image {
						width: 100%;
						height: 100%;
						border-radius: 50%;
					}
				}
				.username {
					margin-left: 1vw;
					width: 24vw;
					overflow: hidden;
					white-space: nowrap;
					text-overflow: ellipsis;
				}
				.zan {
					display: flex;
				}
				.createTime {
					font-size: 2vw;
				}
			}
		}
	}
	.content {
		margin-top: 1vh;
		min-height: 20vh;
		/* #ifndef MP-WEIXIN */
		::v-deep img {
			display: block;
			margin: 0 auto;
			max-width: 80vw;
		}
		/* #endif */
	}
	// 评论
	.list {
		margin-top: 3vh;
		border-top: 3px solid #eee;
		padding-bottom: 8vh;
		width: 100%;
		min-height: 20vh;
		.blog_com {
			font-size: 20px;
			line-height: 5vh;
		}
		.list_item {
			box-sizing: border-box;
			padding: 0 3vw 1vh;
			margin-bottom: 1vh;
			border-bottom: 1px solid #eee;
			.list_con {
				display: flex;
				.list_item_l {
					width: 90%;
					&:active {
						background-color: #eee;
					}
					.commentor {
						display: flex;
						align-items: center;
						width: 100%;
						.avatar {
							margin-right: 2vw;
							width: 10vw;
							height: 10vw;
							image {
								width: 100%;
								height: 100%;
								border-radius: 50%;
							}
						}
					}
					.comment_time {
						color: #666;
						font-size: 14px;
					}

					.comment_text {
						margin-top: 1vh;
						padding: 0 3vw;
					}
				}
				.list_item_r {
					flex-grow: 1;
					display: flex;
					flex-direction: column;
					align-items: center;
					justify-content: center;
					.like_coount {
						color: #9ca8b8;
					}
				}
			}
			.reply_box {
				display: flex;
				.reply_l {
					width: 90%;
					&:active {
						background-color: #eee;
					}
				}
				.reply_r {
					flex-grow: 1;
					display: flex;
					flex-direction: column;
					align-items: center;
					justify-content: center;
				}
			}
			.reply {
				width: 80%;
				padding: 0 5vw;
				margin-top: 1vh;
				.reply_info {
					display: flex;
					align-items: center;
				}
				.reply_time {
					font-size: 12px;
					padding: 0 7vw;
					color: #666;
				}
				.reply_user {
					display: flex;
					align-items: center;
				}
				.reply_user_img {
					width: 7vw;
					height: 7vw;
					margin-right: 1vw;
					image {
						width: 100%;
						height: 100%;
						border-radius: 50%;
					}
				}
				.icon {
					margin: 0 3vw;
				}
			}
			.reply_con {
				margin-top: 0.5vh;
				width: 80%;
				padding: 0 11vw;
			}
			.del {
				padding-left: 2vw;
				text-decoration: underline;
			}
		}
	}
	// 底部
	.footer {
		display: flex;
		justify-content: space-between;
		align-items: center;
		box-sizing: border-box;
		width: 100%;
		padding: 0 3vw;
		height: 7vh;
		position: fixed;
		bottom: 0;
		left: 0;
		background-color: #fff;
		.inp {
			position: relative;
			::v-deep .uni-input-input,
			::v-deep .uni-input-placeholder {
				padding-left: 3vw;
				padding-right: 6vw;
				box-sizing: border-box;
			}
			::v-deep .u-icon {
				position: absolute;
				top: 50%;
				transform: translateY(-50%);
				right: 2.5vw;
				z-index: 99;
				width: 6vw;
				height: 6vw;
				display: flex;
				justify-content: center;
				align-items: center;
			}
		}
		/* #ifdef MP-WEIXIN */
		::v-deep .u-input__content__field-wrapper__field {
			padding-left: 3vw;
			padding-right: 6vw;
			box-sizing: border-box;
		}
		/* #endif */
		::v-deep .u-input {
			width: 46vw;
			height: 5vh;
			padding-left: 2vw;
			box-sizing: border-box;
			background-color: #eee;
		}
		.hudong {
			display: flex;
			view {
				display: flex;
				margin-left: 1vw;
				color: #9ca8b8;
			}
		}
	}
	// 弹出层
	.login_wrapper {
		padding: 10vw;
	}
}
</style>
